package com.ruoyi.system.util;
import java.security.SecureRandom;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
public class UniqueIdGenerator {
    private static final SecureRandom RANDOM = new SecureRandom();
    private static final int MAX_ATTEMPTS = 1000;
    private static final ConcurrentHashMap<Long, AtomicInteger> COUNTER_MAP = new ConcurrentHashMap<>();

    public static synchronized String generateId() {
        long timestamp = System.currentTimeMillis() / 1000; // 精确到秒
        COUNTER_MAP.putIfAbsent(timestamp, new AtomicInteger(0));
        AtomicInteger counter = COUNTER_MAP.get(timestamp);

        // 每毫秒可生成1000个唯一ID
        int count = counter.getAndIncrement();
        if (count > 999) {
            // 等待下一毫秒
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            return generateId();
        }

        // 格式: [3位时间戳][3位计数器][4位随机数]
        String timePart = String.format("%03d", (int) (timestamp % 1000));
        String counterPart = String.format("%03d", count);
        String randomPart = String.format("%04d", RANDOM.nextInt(10000));

        return timePart + counterPart + randomPart;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            System.out.println(generateId());
        }
    }
}
